/**
 *
 */
package com.bobo.web.provider.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yangbo
 * @date 2018-10-22
 * @filename RedisUtils.java
 */
@Component
public class RedisUtils {
    private Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class.getSimpleName());
    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 添加
     *
     * @param key
     * @param object
     * @return
     */
    public Boolean add(String key, Object object) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        redisTemplate.opsForValue().set(key, object);
        if (redisTemplate.opsForValue().get(key) != null) {
            return true;
        }
        return false;
    }

    /**
     * 添加含有过期时间的key
     *
     * @param key
     * @param object
     * @return
     */
    public Boolean add(String key, Object object, long timeout, TimeUnit unit) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        redisTemplate.opsForValue().set(key, object, timeout, unit);
        if (redisTemplate.opsForValue().get(key) != null) {
            return true;
        }
        return false;
    }

    /**
     * 查询
     *
     * @param key
     * @return
     */
    public Object getValueBykeys(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            LOGGER.error("get value from redis error! key:{}", key, e);
            return null;
        }

    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public void deleteValueBykeys(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 根据key批量删除
     *
     * @param keys
     * @return
     */
    public void deleteValueBykeys(List<String> keys) {
        redisTemplate.delete(keys);
    }

    /**
     * 设置key的超时时间
     *
     * @param key      key字符串
     * @param timeout  超时时间
     * @param timeUnit 时间单位
     * @return
     */
    public boolean expire(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }

    /**
     * 根据key获取过期时间并换算成指定单位
     *
     * @param key
     * @param timeUnit
     * @return
     */
    public Long getExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 递增
     */
    public Long increment(String key, long num) {
        return redisTemplate.opsForValue().increment(key, num);
    }

}
